package com.nexgo.payment.pack;

import com.nexgo.common.ByteUtils;
import com.nexgo.common.TlvUtils;
import com.nexgo.data.entity.SendData;
import com.nexgo.data.entity.SendDataBuilder;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.TransRecord;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.util.EmvUtils;
import com.nexgo.payment.util.MessageHelper;
import com.nexgo.payment.util.StringUtils;

import java8.util.Optional;

/**
 * Created by xiaox on 2017/9/15.
 */

class UploadIccOfflineBuilder extends DataBuilder {

    private final TransRecord mTransRecord;
    private final TransType mOrgTransType;

    UploadIccOfflineBuilder(TransData transData, DataSource repository) {
        super(transData, repository);
        mTransRecord = mRepository.queryTransRecord(mTransData.getOrgTraceNum());
        mOrgTransType = TransType.values()[mTransRecord.getTransType()];
    }

    @Override
    SendData form() {
        SendData sendData = new SendDataBuilder().setListener(mListener).setSignListener(mSignListener).createSendData();
        sendData.setHeader(MessageHelper.formMessageHeader(mRepository.getParamValue(PreferencesConstants.TPDU)));
        sendData.setMsgType(mTransData.getTransType().getMsgType());
        sendData.setPan(mTransRecord.getPan());
        sendData.setProcCode(mTransData.getTransType().getProcCode());
        sendData.setAmount(StringUtils.leftPad(mTransRecord.getAmount(), 12, '0'));
        //lr
        sendData.setTraceNum(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        setCurruntTraceNumber(mRepository.getParamValue(PreferencesConstants.TRACE_NUMBER));
        mRepository.increaseTraceNumber();

        sendData.setTime(mTransRecord.getTime());
        sendData.setDate(mTransRecord.getDate());

        sendData.setExpDate(mTransRecord.getExpDate());
        String entryMode = mTransRecord.getEntryMode();
        sendData.setEntryMode(new StringBuilder(entryMode).replace(entryMode.length() - 1, entryMode.length(), "2").toString());
        sendData.setCsn(mTransRecord.getCsn());
        sendData.setConditionCode(mOrgTransType.getConditionCode());
        sendData.setTerminalId(mTransRecord.getTerminalId());
        sendData.setMerchantId(mTransRecord.getMerchantId());
        sendData.setFundType(mTransRecord.getFundType());
        sendData.setEmvTlv(mTransRecord.getEmvTlv());
        sendData.setField62(formField62());
        sendData.setField60(mTransRecord.getField60());
        sendData.setMac("0000000000000000");
        return sendData;
    }

    public String formField62() {
        StringBuilder sb = new StringBuilder();
//        sb.append(mTransData.getTransType().getFuncCode());
        sb.append(mRepository.getParamValue(PreferencesConstants.BATCH_NUMBER));
        sb.append(getCurruntTraceNumber());
        return sb.toString();
    }


    private String formField63() {
        return Optional.ofNullable(mTransRecord.getResultTlv())
                .map(s -> TlvUtils.decodingTLV(s, "9f06"))
                .filter(strings -> strings.size() != 0)
                .map(strings -> strings.get(0))
                .map(s -> EmvUtils.getInterCodeByAid(s))
                .orElse("000");
    }

    private String formField60() {
        StringBuilder sb = new StringBuilder();
        sb.append(StringUtils.firstNonEmpty(mOrgTransType.getFuncCode(), "00"));
        sb.append(StringUtils.firstNonEmpty(mTransRecord.getBatchNum(), mRepository.getParamValue(PreferencesConstants.BATCH_NUMBER)));
        sb.append("000");
        sb.append("6");
        sb.append("0");
        return ByteUtils.byteArray2HexString(sb.toString().getBytes());
    }
}
